package com.bls.cate.ui.activity.person_info_change;

import android.content.Intent;
import android.os.Environment;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.blslib.eventbus.Event;
import com.bls.blslib.eventbus.EventBusUtils;
import com.bls.cate.R;
import com.bls.cate.constant.EventBusCode;
import com.bls.cate.constant.Interface;
import com.bls.cate.constant.Keys;
import com.bls.cate.model.LoginSpRes;
import com.bls.cate.model.RootRes;
import com.bls.cate.ui.widget.TitleView;
import com.bls.cate.utils.AccountUtil;
import com.bls.cate.utils.FrescoImageLoader;
import com.bls.cate.utils.GlideImageLoader;
import com.bls.cate.utils.TxObjectStorage;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.model.CosXmlResultListener;
import com.tencent.cos.xml.model.object.PutObjectRequest;

import java.io.File;
import java.util.ArrayList;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 　　  () 　　　  ()
 * 　　  ( ) 　　　( )
 * 　　  ( ) 　　　( )
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　┻　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ——————————————————
 * Created by BinglingSu on 2018/1/10.
 */

public class SetHeaderActivity extends BaseActivity implements TitleView.OnTitleClickListener {

    private TitleView titleView;
    private SimpleDraweeView ivImage;

    private SetHeaderActivity mActivity;
    public final int REQUEST_CODE_SELECT = 100;
    private static final int SCREEN_WIDTH = ScreenUtils.getScreenWidth();
    private CosXmlService cosXmlService;
    private String uniqueId;
    private String headerImg;


    @Override
    protected void initParams() {
        Intent intent = getIntent();
        uniqueId = intent.getStringExtra("UniqueId");
        headerImg = intent.getStringExtra("HeaderImg");
        mActivity = (SetHeaderActivity) getActivity();
        cosXmlService = new TxObjectStorage().getCosXmlService(getApplicationContext());
        initImgPicker();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_header;
    }

    @Override
    protected void initFvb() {
        titleView = findViewById(R.id.title_view);
        ivImage = findViewById(R.id.iv_image);
    }

    @Override
    protected void initTitle() {
        titleView.setTitleMiddleText("头像");
        titleView.setBtnMode(2, 2);
        titleView.titleRightTv.setText("修改");
        titleView.setTitleClickListener(this);
    }

    @Override
    protected void initView() {
        FrescoImageLoader.showImage(ivImage, headerImg);
    }

    @Override
    public void onTitleClick(int btnType) {
        if (btnType == 2)
            finish();
        else if (btnType == 4)
            btnEventPickerHeader();
    }

    private void initImgPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth((SCREEN_WIDTH));                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight((SCREEN_WIDTH));                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX((SCREEN_WIDTH));                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY((SCREEN_WIDTH));                         //保存文件的高度。单位像素
    }

    /**
     * 选择上传图片
     */
    private void btnEventPickerHeader() {
        Intent intent = new Intent(mActivity, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                final ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    Luban.with(getActivity()).load(images.get(0).path).setTargetDir(getPath()).setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            upLoadHeader(file.getAbsolutePath());
                        }

                        @Override
                        public void onError(Throwable e) {
                            upLoadHeader(images.get(0).getPath());
                        }
                    }).launch();
                }
            }
        }
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Cate/images/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private void upLoadHeader(String path) {
        FrescoImageLoader.showImageFile(ivImage, path);
        String cosPath = "/header/" + uniqueId + "_Large_" + TimeUtils.getNowMills() + ".png"; //格式如 cosPath = "/test.txt";
        PutObjectRequest putObjectRequest = new PutObjectRequest(Keys.TX_OBJECT_STORAGE.TX_OBJECT_STORAGE_BUCKET, cosPath, path);
        putObjectRequest.setSign(6000, null, null);
        cosXmlService.putObjectAsync(putObjectRequest, new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                presenter.requestStrData(Interface.INTERFACE_CODE_Update_HeaderImg, Interface.INTERFACE_USERINFO, CacheMode.NO_CACHE,
                        new HttpParams("RequestMethod", "Header"),
                        new HttpParams("UniqueId", uniqueId),
                        new HttpParams("HeaderImg", result.accessUrl));
            }

            @Override
            public void onFail(CosXmlRequest cosXmlRequest, CosXmlClientException clientException, CosXmlServiceException serviceException) {
                String errorMsg = clientException != null ? clientException.toString() : serviceException.toString();
                LogUtils.i("TEST", errorMsg);
                ToastUtils.showShort("修改失败");
            }
        });
    }


    @Override
    public void showOnSuccess(int requestId, String responseBody, Response response) {
        super.showOnSuccess(requestId, responseBody, response);
        if (requestId == Interface.INTERFACE_CODE_Update_HeaderImg) {
            RootRes rootRes = gson.fromJson(responseBody, RootRes.class);
            ToastUtils.showShort(rootRes.getResultDes());
            if (rootRes.isResultStatus()) {
                String headerImgNew = (String) rootRes.getResultData();
                LoginSpRes loginSpRes = AccountUtil.getStrLoginSp();
                if (loginSpRes != null) {
                    loginSpRes.setHeaderImgSmall(headerImgNew);
                    loginSpRes.setHeaderImgMiddle(headerImgNew);
                    loginSpRes.setHeaderImgLarge(headerImgNew);
                    AccountUtil.updateLoginSp(loginSpRes);
                    EventBusUtils.sendStickyEvent(new Event(EventBusCode.ChangeUserInfo_Refresh));
                }
            }
        }
    }
}
